#include "TFT.h"

CST816S touch(21, 22, -1, 16); // sda, scl, rst, irq

TFT_eSPI tft = TFT_eSPI(); /* TFT instance */

static const uint16_t screenWidth = 280;
static const uint16_t screenHeight = 240;
static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf[280 * 20];

// 函数：my_disp_flush
// 功能：刷新显示
// 参数：disp - 显示驱动器
//       area - 需要刷新的区域
//       color_p - 需要刷新的颜色
void my_disp_flush(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p)
{
  // 计算需要刷新的区域的宽度和高度
  uint32_t w = (area->x2 - area->x1 + 1);
  uint32_t h = (area->y2 - area->y1 + 1);

  // 开始写入
  tft.startWrite();
  // 设置写入窗口
  tft.setAddrWindow(area->x1, area->y1, w, h);
  // 将颜色写入
  tft.pushColors((uint16_t *)&color_p->full, w * h, true);
  // 结束写入
  tft.endWrite();

  // 刷新完成
  lv_disp_flush_ready(disp);
}

void my_touchpad_read(lv_indev_drv_t *indev_driver, lv_indev_data_t *data)
{

  // 检查触摸屏是否可用
  if (touch.available())
  {
    // 设置触摸状态为按下
    data->state = LV_INDEV_STATE_PR;
    /*Set the coordinates*/
    data->point.x = touch.data.y;
    data->point.y = 240 - touch.data.x;
    // Serial.print("Data x ");
    // Serial.println(touch.data.x);
    // Serial.print("Data y ");
    // Serial.println(touch.data.y);
  }
  else
  {
    data->state = LV_INDEV_STATE_REL;
  }
}


void TFT_Init(void)
{
    touch.begin();
    tft.begin();
    tft.setRotation(1);

    lv_init();
    tft.fillScreen(TFT_BLACK);

    lv_disp_draw_buf_init(&draw_buf, buf, NULL, screenWidth * 10);

    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);

    disp_drv.hor_res = screenWidth;
    disp_drv.ver_res = screenHeight;
    disp_drv.flush_cb = my_disp_flush;
    disp_drv.draw_buf = &draw_buf;
    lv_disp_drv_register(&disp_drv);

    static lv_indev_drv_t indev_drv;
    lv_indev_drv_init(&indev_drv);
    indev_drv.type = LV_INDEV_TYPE_POINTER;
    indev_drv.read_cb = my_touchpad_read;
    lv_indev_drv_register(&indev_drv);
}
